<template>
  <div>
    <van-row :gutter="[10, 10]">
      <van-col v-for="(item,index) in dateSelectArr" :key="index" span="8" class="centered-col">
        <van-button :type="item.value == selectDateType ? 'primary' : 'default'"
                    style="width:100%"
                    plain
                    @click="selectDate(item.value)">
          {{ item.name }}
        </van-button>
      </van-col>
    </van-row>
    <div v-if="selectDateType == 'custom'" class="mt-4">
      <van-field>
        <template #input>
          <van-cell
              title="开始时间"
              :value="formattedStartDate"
              is-link
              @click="showStartPicker = true"
          />
        </template>
      </van-field>
      <van-popup v-model:show="showStartPicker" :close-on-click-overlay="false"  position="bottom">
        <van-date-picker
            v-model="tempStartDateArray"
            type="date"
            :min-date="minDate"
            :max-date="maxDate"
            :formatter="formatter"
            @confirm="onStartConfirm"
            @cancel="onStartCancel"
        />
      </van-popup>

      <van-field>
        <template #input>
          <van-cell
              title="结束时间"
              :value="formattedEndDate"
              is-link
              @click="showEndPicker = true"
          />
        </template>
      </van-field>
      <van-popup v-model:show="showEndPicker" :close-on-click-overlay="false"  position="bottom">
        <van-date-picker
            v-model="tempEndDateArray"
            type="date"
            :min-date="minDate"
            :max-date="maxDate"
            :formatter="formatter"
            @confirm="onEndConfirm"
            @cancel="onEndCancel"
        />
      </van-popup>
    </div>

  </div>
</template>

<script setup lang="ts">
import {ref, watch,PropType} from 'vue'
import { PickerOption } from 'vant';

import {
  addDays,
  format,
  startOfToday,
  endOfToday,
  startOfYesterday,
  endOfYesterday,
  startOfWeek,
  endOfWeek,
  startOfMonth,
  endOfMonth,
  startOfQuarter,
  endOfQuarter,
  startOfYear,
  endOfYear
} from "date-fns";

const props = defineProps({
  selectDateType: {
    type: String as PropType<string>,
    default: '', // 设置默认值
  },
});

const selectDateType = ref<string>(props.selectDateType)

const emit = defineEmits(['updateParentSelectDataType']);


interface DateOption {
  name: string;
  value: string;
}

const dateSelectArr: DateOption[] = [
  { name: "今天", value: "day" },
  { name: "昨天", value: "yesterday" },
  { name: "本周", value: "week" },
  { name: "本月", value: "month" },
  { name: "本季度", value: "quarter" },
  { name: "今年", value: "year" },
  { name: "最近1周", value: "-7" },
  { name: "最近3周", value: "-21" },
  { name: "最近1个月", value: "-30" },
  { name: "最近3个月", value: "-90" },
  { name: "最近半年", value: "-180" },
  { name: "自定义", value: "custom" },
];

const getDateLabel = (value: string): string | undefined => {
  const option = dateSelectArr.find((option) => option.value === value);
  return option ? option.name : undefined;
};

const selectDate = (value:string) => {
  if(selectDateType.value !== value){
    selectDateType.value = value
  } else {
    selectDateType.value = ""
  }
}

watch(selectDateType,function (newValue:string){
  syncSelectDataType(newValue)
})


const showStartPicker = ref(false);
const showEndPicker = ref(false);

// 格式化日期为字符串数组
const today = new Date();
const firstDayOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);

const formatDateArray = (date: Date): string[] => {
  const year = date.getFullYear().toString();
  const month = (date.getMonth() + 1).toString().padStart(2, '0'); // 月份从0开始，需要加1
  const day = date.getDate().toString().padStart(2, '0');

  return [year, month, day];
};


// 初始化 startDateArray
const startDateArray = ref<string[]>(formatDateArray(firstDayOfMonth));
const endDateArray = ref<string[]>(formatDateArray(today));

const tempStartDateArray = ref([...startDateArray.value]);
const tempEndDateArray = ref([...endDateArray.value]);

const formattedStartDate = ref<string>(`${startDateArray.value[0]}-${startDateArray.value[1]}-${startDateArray.value[2]}`);
const formattedEndDate = ref<string>(`${endDateArray.value[0]}-${endDateArray.value[1]}-${endDateArray.value[2]}`);

const minDate = new Date(2024, 1, 1);
const maxDate = new Date(2024, 12, 31);

const formatter = (type:string, option:PickerOption): PickerOption => {
  if (type === 'year') {
    option.text += '年';
  }
  if (type === 'month') {
    option.text += '月';
  }
  if (type === 'day') {
    option.text += '日';
  }
  return option;
};

const onStartConfirm = () => {
  startDateArray.value = [...tempStartDateArray.value];
  formattedStartDate.value = startDateArray.value.join("-")
  showStartPicker.value = false
};
const onStartCancel = () =>{
  tempStartDateArray.value = [...startDateArray.value];
  showStartPicker.value = false
}

const onEndConfirm = () => {
  endDateArray.value = [...tempEndDateArray.value];
  formattedEndDate.value = endDateArray.value.join("-")
  showEndPicker.value = false
};
const onEndCancel = () =>{
  showEndPicker.value = false
  tempEndDateArray.value = [...endDateArray.value];
}

const getRelativeDate = (offset: number): string=> {
  const date = addDays(new Date(), offset);
  return format(date, 'yyyy-MM-dd');
}

const cancelDate = (dataType:string="")=>{
  selectDateType.value = dataType
}

const updateQueryParam = () => {
  if(selectDateType.value){
    switch (selectDateType.value) {
      case 'custom':
        return {
          gte: formattedStartDate.value,
          lte: formattedEndDate.value
        }
      case 'yesterday':
        return {
          gte: format(startOfYesterday(), 'yyyy-MM-dd'),
          lte: format(endOfYesterday(), 'yyyy-MM-dd')
        }
      case 'day':
        return {
          gte: format(startOfToday(), 'yyyy-MM-dd'),
          lte: format(endOfToday(), 'yyyy-MM-dd')
        }
      case 'week':
        return {
          gte: format(startOfWeek(today, { weekStartsOn: 1 }), 'yyyy-MM-dd'),
          lte: format(endOfWeek(today, { weekStartsOn: 1 }), 'yyyy-MM-dd')
        }
      case 'month':
        return {
          gte: format(startOfMonth(today), 'yyyy-MM-dd'),
          lte: format(endOfMonth(today), 'yyyy-MM-dd')
        }
      case 'quarter':
        return {
          gte: format(startOfQuarter(today), 'yyyy-MM-dd'),
          lte: format(endOfQuarter(today), 'yyyy-MM-dd')
        }
      case 'year':
        return {
          gte: format(startOfYear(today), 'yyyy-MM-dd'),
          lte: format(endOfYear(today), 'yyyy-MM-dd')
        }
      default:
        let date =  getRelativeDate(Number(selectDateType.value))
        return {
          gte:date,
          lte: format(endOfToday(), 'yyyy-MM-dd')
        }
    }
  }
  return null;
};
const syncSelectDataType = (newValue:string) => {
  emit('updateParentSelectDataType', newValue,getDateLabel(newValue));
};

// 可选：定义一个方法，可以通过父组件引用来调用
defineExpose({
  triggerConfirm: updateQueryParam,
  triggerCancel: cancelDate
})


</script>

<style scoped>

</style>
